<template>
  <view class="container">
    <!-- 血量 -->
    <!-- <view class="hp-container">
      <text class="hp-text">您的血量余额：400cc</text>
    </view> -->

    <view class="container-1">
      <view class="blood-hp">
        <image src="https://shenai-fducs.oss-cn-shanghai.aliyuncs.com/shenai_interface/eblood_200cc.gif" class="hp-img">
        </image>
      </view>
      <view class="blood-text-container">
        <text class="hp-text">血包能量：{{ assets.bloodBags }}cc</text>

      </view>
    </view>
    <!-- 列表 -->
    <scroll-view scroll-y="true" class="scroll">
      <uni-grid :column="3" :highlight="true" :square="false" @change="change" :show-border="false">
        <uni-grid-item v-for="(item, index) in giftsList" :key="item.id" :index="index" class="grid-item">
          <view class="grid-item-box" style="background-color: #fff;">
            <view class="img-container">
              <image class="img" mode="aspectFill" :src="item.imageUrl"></image>
            </view>
            <view>
              <view class="text-container">
                <text class="text-remain">{{ item.name }}</text>

                <uni-icons v-if="userinfo.role==1" type="trash-filled" @click.native.stop="openDelete(item.id)"
                  size="25" color="#666"></uni-icons>

              </view>
              <view class="text-container">
                <text class="text-price">{{ item.price }}cc</text>
                <text class="text-remain">余量：{{ item.count }}</text>
              </view>
            </view>
          </view>
        </uni-grid-item>
      </uni-grid>
    </scroll-view>

    <view class="right_button filled" @tap="openUpload" v-if="userinfo.role==1">
      <uni-icons type="plusempty" size="30" color="#fff"></uni-icons>

    </view>


    <!-- 新增库存 -->
    <view class="ms_bg" v-show="isOpenUpload" @tap.stop="closeUpload">
    </view>
    <view class="up_box" v-show="isOpenUpload" :style="isUpdate?'height:500rpx':''">
      <view class="close" @tap.stop="closeUpload">

        <uni-icons type="closeempty" size="15" color="#666"></uni-icons>

      </view>
      <view class="ms_portrait">

        <image :src="userinfo.avatarUrl" mode="aspectFill" class="top_box_info_picdiv_pic" />


      </view>



      <view class="up_title"> <text> {{isUpdate?"编辑":"新增"}}库存</text></view>

      <view class="up_textarea">
        <uni-easyinput trim="all" v-model="uploadInfo.name" placeholder="请输入礼物名称" disabled="isUpdate" />
      </view>


      <view class="up_input" style="display: flex;">

        <uni-easyinput trim="all" v-model="uploadInfo.count" placeholder="请输入库存" />
        <view style="width:10px;"></view>
        <uni-easyinput trim="all" v-model="uploadInfo.price" placeholder="请输入血量单价" />
      </view>
      <view class="up_input">


      </view>
<!--      <view class="up_input">
        <uni-data-checkbox v-model="uploadInfo.is_bottle_gift" :localdata="is_bottle_giftOption"></uni-data-checkbox>
      </view> -->
  

      <view class="up_pic" v-if="!isUpdate">
        <!-- <uni-file-picker limit="1" title="支持扩展名: .jpg .png"></uni-file-picker> -->
        <uni-file-picker ref="refImg" file-extname="png,jpg" limit="1" :del-icon="false" disable-preview
          :imageStyles="imageStyles" file-mediatype="image" return-type="object" @select="select">

          <image class="img" v-if="uploadInfo.imageUrl" mode="aspectFill" :src="uploadInfo.imageUrl"></image>
          <uni-icons v-else type="plusempty" size="25" color="#bebebe"></uni-icons>
        </uni-file-picker>
        <view class="up_alert">支持扩展名: .jpg .png</view>

      </view>
      <view class="up_btn" @tap.stop="upSubmit">
        提交
      </view>

    </view>
    <!-- 新增库存 -->


    <!-- 确认兑换弹窗 -->
    <uni-popup ref="popup" type="center" :mask-click="true" class="popup">
      <!-- <view class="popup-container"> -->
      <!-- <view class="title">
					<text class="title-text">确认兑换？</text>
				</view>
				<view class="button">
					<text class="button-exchange" @click="exchangeItem">兑换</text>
					<text class="button-quit" @click="clickToClose">取消</text>
				</view> -->
      <!-- </view> -->

      <view class="card-container">
        <uni-card class="card">
          <!-- <image slot='cover' style="width: 100%;" :src="cover"></image> -->
          <view class="msg-container">
            <text class="msg-text">确认兑换？</text>
          </view>

          <view slot="actions" class="card-actions">
            <view class="confirm-container" @click="exchangeItem()">
              <text class="confirm-text">确定</text>
            </view>
            <view class="quit-container" @click="clickToClose">
              <text class="quit-text">取消</text>
            </view>
          </view>
        </uni-card>
      </view>
    </uni-popup>

    <!-- 删除库存 -->
    <uni-popup ref="deleteDialog" type="dialog">
      <uni-popup-dialog type="error" cancelText="关闭" confirmText="确定" title="删除库存" content="确定删除此库存？"
        @confirm="dialogConfirm()"></uni-popup-dialog>
    </uni-popup>


  </view>



</template>

<script>
  import {
    getGifts,
    exchangeGifts,
    addGifts,
    updateGifts,
    deleteGifts
  } from "@/api/exchange.js";

  import {
    uploadFile,
    getFileUrl
  } from "@/api/home.js";
  // import {
  //   userInfo
  // } from "os";
  export default {
    data() {
      return {

        // 确认兑换
        exchangeId: -1,
        // 测试数据（单个
        testGood: {
          id: 0,
          name: "商品1",
          price: 1000,
          remain: 10,
          image: "/static/img/wechat.png"
        },
        // 商品数据
        giftsList: [],
        // 商品范例数据
        goodsList: [{
            id: 1,
            name: "商品1",
            price: 1000,
            remain: 10,
            type: "咖啡",
            image: "/static/logo.png",
          },
          {
            id: 2,
            name: "商品2",
            price: 2000,
            remain: 20,
            type: "咖啡",
            image: "/static/logo.png",
          },
          {
            id: 3,
            name: "商品3",
            price: 3000,
            remain: 30,
            type: "咖啡",
            image: "/static/logo.png",
          },
          {
            id: 4,
            name: "商品1",
            price: 1000,
            remain: 10,
            type: "咖啡",
            image: "/static/logo.png",
          },
          {
            id: 5,
            name: "商品2",
            price: 2000,
            remain: 20,
            type: "咖啡",
            image: "/static/logo.png",
          },
          {
            id: 6,
            name: "商品3",
            price: 3000,
            remain: 30,
            type: "咖啡",
            image: "/static/logo.png",
          },
          {
            id: 7,
            name: "商品1",
            price: 1000,
            remain: 10,
            type: "咖啡",
            image: "/static/logo.png",
          },
          {
            id: 8,
            name: "商品2",
            price: 2000,
            remain: 20,
            type: "咖啡",
            image: "/static/logo.png",
          },
          {
            id: 9,
            name: "商品3",
            price: 3000,
            remain: 30,
            type: "咖啡",
            image: "/static/logo.png",
          },
          {
            id: 10,
            name: "商品1",
            price: 1000,
            remain: 10,
            type: "咖啡",
            image: "/static/logo.png",
          },
          {
            id: 11,
            name: "商品2",
            price: 2000,
            remain: 20,
            type: "咖啡",
            image: "/static/logo.png",
          },
          {
            id: 12,
            name: "商品3",
            price: 3000,
            remain: 30,
            type: "咖啡",
            image: "/static/logo.png",
          },
        ],
        //以下均是管理员模块
        userinfo: {
          avatarUrl: "",
          
        },
        upSubmitLock :false,
        assets:{bloodBags:0},
        selectImg: {},
        //新增库存表单：
        uploadInfo: {},
        isOpenUpload: false,
        isUpdate: false,

        is_bottle_giftOption: [{
          text: "漂流瓶礼品库存",
          value: true
        }, {
          text: "答题礼品库存",
          value: false
        }],
        // checkphotoSetIntervalId: 0

      };
    },
    onLoad() {
      // this.showPopup();
      this.getGiftsList();
      this.getStorageInfo();

    },
    methods: {
      listLength() {
        return this.goodsList.length;
      },
      getStorageInfo() {
        this.userinfo = wx.getStorageSync('shenai_userInfo')
        this.assets = wx.getStorageSync('shenai_userAssetsInfo')
      },
      getGiftsList() {
        let param = {};
        if (this.userinfo.role==1) {
          param = {
            all_gift: true
          };
        }
        uni.$once('refreshUserinfo', (param) => {
          this.getStorageInfo()

        })

        getGifts(param).then(res => {
          console.log("请求礼物信息");
          this.giftsList = res.data.data;
      
        })

      },

      postExchangeGifts() {
        const gift_id = {
          giftId: this.exchangeId
        };
        exchangeGifts(gift_id).then(response => {
            uni.$emit('needRefresh', true);
            this.getGiftsList();
            console.log(response);
          })
          .catch(error => {
            console.error(error);
          })
      },
      // 用户点击某个格子
      change(e) {
        console.log("e")
        console.log(e)
        let index = e.detail.index;

        // 选择
        this.exchangeId = this.giftsList[index].id;
        //管理员动作
        if (this.userinfo.role==1) {
          this.isUpdate = true;

          this.uploadInfo = this.giftsList[index];
          console.log(this.giftsList)
          console.log(this.uploadInfo)
          this.openUpload()
          return;
        }else{
          if(this.giftsList[index].count<=0){
            uni.showToast({
              title: `库存不足`,
              icon: 'none'
            });
            return;
          }
          
        }
        // 弹窗
        this.showPopup()
      },
      showPopup() {
        this.$refs.popup.open();
      },
      clickToClose() {
        this.$refs.popup.close();
      },
      // 确认兑换
      exchangeItem() {
        this.postExchangeGifts();
        uni.showToast({
          title: `兑换了id为${this.exchangeId}的奖品`,
          icon: 'none'
        });
        this.exchangeId = -1; // 重置id

        this.clickToClose();
      },

      //以下全为管理员新增库存
      openUpload(e) {
        this.isOpenUpload = true;
      },
      closeUpload() {
        this.isOpenUpload = false;
        this.initForm();

      },
      //初始化库存表单
      initForm() {
        if(!this.isUpdate)
          this.$refs.refImg.clearFiles();
        this.isUpdate = false;
        this.uploadInfo = {};
        this.selectImg = {};
        
      },
      select(e) {
        console.log("selectimg",e)
        //保留以后可能会限制大小，size单位为字节 if(e.tempFiles[0].size)
        this.selectImg = e;
      },
      async upSubmit() {
        if(this.upSubmitLock) return;
        this.upSubmitLock = true;
        // {
        //     "name":"可乐",
        //     "remain_num": 999,
        //     "price": 100,
        //     "image": "",
        //     "description":""
        // }

        if (!this.uploadInfo.name) {
          uni.showToast({
            title: `请输入礼物名称`,
            icon: 'none'
          });
          this.upSubmitLock = false;
          return;
        }

        if (!this.uploadInfo.count) {
          uni.showToast({
            title: `请输入库存`,
            icon: 'none'
          });
          this.upSubmitLock = false;
          return;
        }

        if (!this.uploadInfo.price) {
          uni.showToast({
            title: `请输入血量单价cdk`,
            icon: 'none'
          });
          this.upSubmitLock = false;
          return;
        }

        if (this.uploadInfo.imageUrl == '' && Object.keys(this.selectImg).length == 0) {
          uni.showToast({
            title: `请上传图片`,
            icon: 'none'
          });
          this.upSubmitLock = false;
          return;
        }
        if (Object.keys(this.selectImg).length != 0) {
          let imagData = await uploadFile(this.selectImg);
          
          this.uploadInfo.imageUrl = imagData;
          

        } else delete this.uploadInfo.imageUrl;
        console.log("uploadInfo");
        console.log(this.uploadInfo);
        if (this.isUpdate) {
          this.uploadInfo.id = this.exchangeId;
           await updateGifts(this.uploadInfo);
        }
        else await addGifts(this.uploadInfo);
        //这个要着干嘛的
        // this.checkphotoSetIntervalId = setTimeout(() => {
        //   this.getGiftsList();
        // }, 1500);
        this.isOpenUpload = false;
        this.initForm();
        this.getGiftsList();
  this.upSubmitLock = false;


      },

      openDelete(id) {
        this.$refs.deleteDialog.open();
        this.exchangeId = id;
      },
      dialogConfirm() {
        deleteGifts( this.exchangeId
        ).then(res => {
          this.getGiftsList();
          uni.showToast({
            title: `删除成功`,
            icon: 'none'
          })
        })
      }
      //管理员新增内存结束
    }
  }
</script>

<style lang="scss">
  .container {
    display: flex;
    flex-direction: column;
    align-items: center;
    background-color: white;
  }

  .hp-container {
    height: 100rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-items: center;
  }

  .hp-text {}


  .scroll {
    height: calc(100vh - 100rpx); // 注意空格
  }

  .grid-item {
    background-color: white;
  }

  .grid-item-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-items: center;
    padding: 15rpx 0;
  }

  .img-container {
    // border: 1rpx solid #EE8671;
    // border-radius: 20rpx;
  }

  .img {
    width: 160rpx;
    height: 160rpx;
  }

  .text-price {
    margin: 10rpx;
    font-size: 20rpx;
    color: #EE8671;
  }

  .text-remain {
    margin: 10rpx;
    font-size: 20rpx;
  }

  // .popup-container {
  // 	width: 550rpx;
  // 	height: 350rpx;
  // 	align-items: center;
  // 	display: flex;
  // 	flex-direction: column;
  // 	background-color: rgba(255, 255, 255, 0.9);
  // 	border-radius: 20rpx;
  // }

  // .title {
  // 	position: absolute;
  // 	top: 150rpx;
  // 	display: flex;
  // 	flex-direction: column;
  // 	align-items: center;
  // 	justify-items: center;
  // }

  // .title-text {
  // 	font-size: 50rpx;
  // }

  // .button {
  // 	position: absolute;
  // 	bottom: 40rpx;
  // 	display: flex;
  // 	flex-direction: row;
  // }

  // .button-exchange {
  // 	margin-right: 20rpx;
  // }

  // .button-quit {
  // 	margin-left: 20rpx;
  // }

  .card-container {
    width: 550rpx;
    height: 350rpx;
  }

  .card {
    display: flex;
    flex-direction: column;
    // justify-content: center;
    align-items: stretch;
  }

  .msg-container {
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .card-actions {
    display: flex;
    justify-content: space-around;
    width: 100%;
    height: 50rpx;
  }

  .confirm-container {}

  .container-1 {
    background-color: white;
    position: relative;
    // top: 250rpx;
    display: flex;
    flex-direction: row;
    // border: 1rpx solid #EE8671;
    // background-color: white;
    // border-radius: 20rpx;
    // width: 80vw;
    border-style: hidden hidden dashed hidden;
    border-color: #b5b5b5;
    border-width: 1rpx;
    height: 250rpx;
    justify-content: center;
    align-items: center;
    margin: 20rpx;
  }

  .blood-hp {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }

  .hp-img {
    // width: 200rpx;
    // height: 200rpx;
    width: 250rpx;
    height: 250rpx;
    margin-right: 55rpx;
  }

  .blood-text-container {
    background-color: #EE8671;
    color: white;
    width: 45vw;
    height: 100rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    border-radius: 10rpx;
    justify-content: center;
    font-size: 14px;
  }

  .hp-text {
    margin: 10rpx;
  }

  .right_button {

    position: absolute;
    z-index: 99;
    // background-color: white;
    right: 45rpx;
    border-radius: 50%;
    top: calc(100% - 125rpx);

  }

  .filled {
    height: 40px;
    width: 40px;
    background-color: #ff7f6a;
    display: flex;
    justify-content: center;
    align-items: center;
    box-shadow: 2rpx 2rpx 10rpx #999999;
  }



  //以下为新增库存表单
  .ms_bg {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0);
    z-index: 10;

  }


  .up_box {
    font-size: 27rpx;
    position: absolute;
    z-index: 999;
    background-color: white;
    padding: 20rpx 20rpx 0;
    bottom: 0rpx;
    border-radius: 12rpx;

    box-shadow: 2rpx 2rpx 10rpx #999999;
    height: 780rpx;
    width: calc(100vw - 60rpx);
    overflow: hidden;
    left: 0;
    right: 0;
    margin: 0 auto;


    // position: relative;

    .title {
      color: #999999;
    }

    .swiper_text {
      margin-right: 50rpx;
    }

    .row {
      margin-bottom: 15rpx;
    }

    .main_pic {
      height: 280rpx;
      width: 570rpx;
      object-fit: contain;
      position: fixed;
      right: 35rpx;
      margin-top: 40rpx;
    }

    .up_title {
      height: 60rpx;
      width: 330rpx;
      position: fixed;
      right: 167rpx;
      margin-top: 40rpx;
      font-weight: bold;
      border-radius: 30rpx;
      background-color: #f6f6f6;
      text-align: center;

      text {
        vertical-align: middle;
        line-height: 60rpx;
      }
    }

    .up_textarea {
      margin-top: 170rpx;

      // height: 140rpx;
      .uni-easyinput__content-textarea {
        height: 120rpx;
        min-height: 120rpx;
      }
    }

    .up_input {
      margin-top: 20rpx;
    }

    .up_pic {
      margin-top: 20rpx;
      display: flex;
      position: relative;

      .up_alert {
        // height: 60rpx;
        position: absolute;
        bottom: 10rpx;
        margin-left: 120px;
        font-size: 12px;
        color: #999999;
      }


    }

    .choose_ad {
      margin-top: 20rpx;
      height: 70rpx;
      border-radius: 7rpx;
      border: 1px solid #e5e5e5;
      display: flex;
      padding: 0 20rpx;
      justify-content: space-between;

      text {
        vertical-align: middle;
        line-height: 70rpx;
      }


    }

    .up_btn {
      background-color: #ff7f6a;
      height: 70rpx;
      text-align: center;
      line-height: 70rpx;
      color: #fff;
      border-radius: 10rpx;
      margin-top: 20rpx;


    }

    .close {
      position: fixed;
      right: 30rpx;
    }

    .times {
      height: 40rpx;
      width: 70rpx;
      background-color: #999999;
      color: #fff;
      bottom: 10rpx;
      text-align: center;
      border-radius: 0 0 10rpx 0;

    }



    .info_card {
      // position: fixed;
      margin: 350rpx 20rpx 0;
      // height: 300rpx;
    }

    .ms_portrait {
      height: 130rpx;
      width: 130rpx;
      position: fixed;
      left: 50rpx;
      z-index: 1;


      image {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 50%;
        border-color: #fff;
        border: 1px solid #fff;
        box-shadow: 2rpx 2rpx 10rpx #707070;
      }
    }
  }
</style>